
// 懒汉模式, 线程安全

#include <mutex>
#include <iostream>
#include <thread>
#include <string>
#include <atomic>
template <typename T>
class Singleton {
    volatile static T* inst; // 需要设置 volatile 关键字, 否则可能被编译器优化.
    static std::mutex lock;
public:
    static T* GetInstance() {
    if (inst == NULL) { // 双重判定空指针, 降低锁冲突的概率, 提高性能.
    lock.lock(); // 使用互斥锁, 保证多线程情况下也只调用一次 new.
    if (inst == NULL) {
        inst = new T();
        std::cout << "new T()" << std::endl;}
    lock.unlock();
}
    return inst;
}

    // 禁用拷贝和移动
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;
private:
    Singleton() = default;
    ~Singleton() = default;
};